#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
# Reason-GPL: import-scapy
import random
import socket
import sys
from scapy.all import IP, TCP, ICMP, Ether, get_if_hwaddr, get_if_list, sendp

def get_if():
    """获取主机 eth0 接口"""
    iface = None
    for i in get_if_list():
        if "eth0" in i:
            iface = i
            break
    if not iface:
        print("Cannot find eth0 interface")
        exit(1)
    return iface

def writeArp_matchRules(p4info_helper, sw, match_fields_1, match_fields_2, action_params):
    table_entry = p4info_helper.buildTableEntry(
        table_name="MyIngress.arp_match",
    )

def main():
    if len(sys.argv) < 2:
        print("Usage: python3 send.py <destination_ip> [message]")
        exit(1)

    dst_ip = sys.argv[1]  # 目标IP（如 h2 的 10.0.2.2）
    message = sys.argv[2] if len(sys.argv) > 2 else "P4_LEVEL2_TEST"
    iface = get_if()

    # 构造以太网 + IPv4 + ICMP/TCP 包
    pkt = Ether(src=get_if_hwaddr(iface), dst="ff:ff:ff:ff:ff:ff")  # 广播MAC（由交换机处理）
    pkt = pkt / IP(dst=dst_ip) / ICMP() / message  # 使用ICMP（ping协议）
    # 如果需要TCP，替换为：TCP(dport=1234, sport=random.randint(49152,65535)) / message

    print(f"Sending packet on {iface} to {dst_ip}:")
    pkt.show2()  # 打印包结构
    sendp(pkt, iface=iface, verbose=False)

if __name__ == '__main__':
    main()
